package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfo;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.AddressService;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private AddressDao addressDao;

    @Override
    public Result order(OrderInfo orderInfo) throws Exception {
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = orderInfo.getOrderDate();
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = orderInfo.getTelephone();
        Member member = memberDao.findByTelephone(telephone);
            if (member != null) {
                Integer id = member.getId();//获取会员ID
                Date date = DateUtils.parseString2Date(orderDate);//获取预定日期
            String setmealId = orderInfo.getSetmealId();//获取套餐类型
            Order order = new Order(id, date, Integer.parseInt(setmealId));
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }
        //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        if (member == null) {
            member = new Member();
            member.setName(orderInfo.getName());
            member.setPhoneNumber(orderInfo.getTelephone());
            member.setIdCard(orderInfo.getIdCard());
            member.setSex(orderInfo.getSex());
            member.setRegTime(new Date());
            memberDao.add(member);
        }
        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType(orderInfo.getOrderType());
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态,未到诊
        order.setSetmealId(Integer.parseInt(orderInfo.getSetmealId()));
        orderDao.add(order);
        setAddressAndOrder(order.getId(),Integer.parseInt(orderInfo.getAddress()));
        //添加预约成功后,设置已预约人数+1
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);


        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    @Override
    public Map findById(Integer id) throws Exception {
        return orderDao.findById4Detail(id);
    }

    @Override
    public List<String> findDateTime(String startDate, String endDate) throws Exception {
        return null;
    }

    @Override
    public List<Integer> findBookingCount(List<String> dates) {
        List<Integer> listBooking = new ArrayList<>();
        for (String date : dates) {   //遍历每一天
            Integer count = orderDao.findOrderCountByDate(date);  //调用方法查询每一天
            listBooking.add(count);
        }
        return listBooking;
    }

    @Override
    public List<Integer> findConfirmedCount(List<String> dates) {
        List<Integer> listConfirmed = new ArrayList<>();
        for (String date : dates) {
            Integer count = orderDao.findVisitsCountByDate(date);
            listConfirmed.add(count);
        }
        return listConfirmed;
    }

    //建立检查组和检查项关系
    public void setAddressAndOrder(Integer orderId,Integer addressId){
        //设置检查组和检查项之间多对多的关联关系,添加中间表数据(主要要获得检查项中新生成的ID)
                Map<String, Integer> map = new HashMap();
                map.put("orderId", orderId);
                map.put("addressId", addressId);
                orderDao.setAddressAndOrder(map);
    }
}
